<template>
	<div class="modal" v-on:keyup.esc="dismiss" v-show="show">
		<div class="modal-dialog">
			<div class="modal-content">
				<input class="search-bar" type="text" v-bind:placeholder="hint" v-model="userInput" v-on:keyup.enter="onEnter">
				<a href="#" class="go-icon" v-on:click="onEnter">
					<svg width="24" height="24" viewBox="0 0 24 24">
						<path d="M4,11V13H16L10.5,18.5L11.92,19.92L19.84,12L11.92,4.08L10.5,5.5L16,11H4Z"></path>
					</svg>
				</a>
				<div class="result-container" v-if="showResult">
					<minibar v-for="result in results" v-bind:accountid="result" v-bind:key="result"></minibar>
				</div>
			</div>
		</div>
	</div>
</template>

<script>
import {bus} from '../main.js'
import MiniAccountBar from './MiniAccountBar'

export default{
	name: 'searchbox',
	components: {
		minibar: MiniAccountBar
	},
	data() {
		return {
			userInput: '',
			show: false,
			showResult: false,
			hint: '搜索条件可以是时间、使用人和用途。按esc关闭。',
			results: null,
			accounts: [],
			showResult: false
		}
	},
	mounted: function(){
		bus.$on('show_search_box', function(){
			this.show = true
		}.bind(this))

		bus.$on('show_detail_modal', function(accountid){
			this.dismiss()
		}.bind(this))

		bus.$on('did_add_account', function(accountid){
			let account = window.delegate.getAccount(accountid)
			this.accounts.push(`${account.purpose} ${account.owner}`)
		})

		for(let i = 0; i < window.delegate.accountList.length; i++){
			let account = window.delegate.getAccount(i)
			this.accounts.push(`${account.purpose} ${account.owner}`)
		}
	},
	methods: {
		onEnter: function(){
			console.log('user clicked enter.')
			this.showResult = false
			this.results = []
			for(let i = 0; i < this.accounts.length; i++){
				if(this.accounts[i].includes(this.userInput)){
					this.results.push(i)
				}
			}
			this.showResult = true
		},

		dismiss: function(){
			this.userInput = ''
			this.showResult = false
			this.show = false
		}, 
	}
}
</script>

<style scoped>

.modal{
	background-color: rgba(133,133,133,0.3);
	position: fixed;
	top: 0px;
	bottom: 0px;
	left: 0px;
	right: 0px;
	outline: 0;
	z-index: 1050;
	opacity: 1;
	box-sizing: border-box;
	font-family: sans-serif;
}

.modal-dialog{
	margin: 150px auto;
	position: relative;
	width: 70%;
}

.search-bar{
	width: 100%;
	height: 50px;
	border-radius: 5px;
	font-size: 24px;
	padding-left: 15px;
	background: white;
	border: 3px solid darkred;
	opacity: 1;
	outline: none;
	color: darkred; 
	text-shadow: 0px 0px 0px black; 
	-webkit-text-fill-color: transparent;
}

.go-icon{
	float: right;
	position: relative;
	top: -40px;
}

.result-container{
	width: 98%;
	padding-left: 15px;
	padding-right: 15px;
	border-radius: 5px;
	font-size: 20px;
	background-color: rgba(255, 255, 255, 0.5);
	position: relative;
	top: 0px;
	padding-bottom: 15px;
	border: 3px solid black;
}

</style>